import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/hj_page/live/live_item_widget.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/banner/ads_grid_view_widget.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/refresh/pull_refresh.dart';
import 'package:tiktokadult/tools_base/widget/card_swiper/src/swiper.dart';

import 'live_model.dart';
import 'live_sub_logic.dart';

//直播子列表页面
class LiveSubPage extends StatefulWidget {
  final LiveModule? tagData;
  const LiveSubPage({Key? key, this.tagData}) : super(key: key);

  @override
  State<LiveSubPage> createState() => _LiveSubPageState();
}

class _LiveSubPageState extends State<LiveSubPage> {
  late LiveSubLogic logic;

  @override
  void initState() {
    super.initState();
    logic = Get.put(LiveSubLogic(tagData: widget.tagData), tag: widget.tagData?.id ?? '');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: GetBuilder<LiveSubLogic>(
        tag: widget.tagData?.id ?? '',
        builder: (_) => pullYsRefresh(
          enablePullUp: _.isRecom ? false : true,
          onInit: (controller) => logic.controller = controller,
          onRefresh: (controller) => _.loadData(),
          onLoading: (controller) => _.loadMoreData(),
          child: _buildContent(_),
        ),
      ),
    );
  }

  Widget _buildContent(LiveSubLogic _) {
    if (_.isRecom) {
      //推荐样式
      if (_.liveMainModel?.recom == null) return LoadingCenterWidget();
      if (_.liveMainModel?.recom?.isEmpty == true)
        return CErrorWidget(
          retryOnTap: () => logic.loadData(),
        );
      return CustomScrollView(
        slivers: _buildScrollItems(),
      );
    } else {
      //列表样式
      return CustomScrollView(
        slivers: [
          _buildADBanner(),
          _buildCapeList(),
        ],
      );
    }
  }

  //列表样式
  _buildCapeList() {
    if (logic.loading) {
      return SliverToBoxAdapter(
          child: SizedBox(
        height: 200,
        child: LoadingCenterWidget(),
      ));
    } else {
      if (logic.liveList.isEmpty) {
        return SliverToBoxAdapter(
          child: CErrorWidget(retryOnTap: () => logic.loadData()),
        );
      } else {
        return SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 12,
              crossAxisSpacing: 7,
              childAspectRatio: 168 / 105,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                LiveAnchor model = logic.liveList[index];
                return LiveItemWidget(showType: 5, anchor: model);
              },
              childCount: logic.liveList.length,
            ),
          ),
        );
      }
    }
  }

  List<Widget> _buildScrollItems() {
    List<Widget> items = [];
    for (var i = 0; i < (logic.liveMainModel?.recom?.length ?? 0); i++) {
      LiveRecom? element = logic.liveMainModel?.recom?[i];
      String showType = element?.recoShowType ?? '';
      Widget widget;
      if (showType == 'nine_grid') {
        widget = _buildNineGrid(element);
      } else if (showType == 'six_round') {
        widget = _buildsSixRound(element);
      } else if (showType == 'four_grid') {
        widget = _buildsFourGrid(element);
      } else if (showType == 'six_grid') {
        widget = _buildsSixGrid(element);
      } else if (showType == 'horizontal_slide') {
        widget = _buildsHorizontalSlide(element);
      } else if (showType == 'list') {
        widget = _buildRecommendList(element?.anchors);
      } else {
        widget = Container();
      }
      //index = 0，包一层
      if (i == 0) {
        widget = Stack(
          children: [
            Positioned.fill(
              child: Image.asset(
                'assets/images/live_images/live_main_bg.webp',
                alignment: Alignment.topCenter,
                fit: BoxFit.cover,
              ),
            ),
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                220.sizeBoxH,
                widget,
                10.sizeBoxH,
              ],
            ),
            Positioned(
              top: 170,
              right: 12,
              child: GestureDetector(
                onTap: () => logic.onChargeAction(),
                child: Image.asset(
                  'assets/images/live_images/live_charge.webp',
                  height: 40,
                ),
              ),
            )
          ],
        );
      }
      items.add(SliverToBoxAdapter(child: widget));
    }
    return items;
  }

//广告banner
  Widget _buildADBanner() {
    return SliverToBoxAdapter(
        child: AdsGridViewWidget(
      35,
      isBigStyle: true,
      isBannerStyle: false,
      padding: EdgeInsets.fromLTRB(16, 15, 16, 15),
    ));
  }

  //九宫格
  _buildNineGrid(LiveRecom? recom) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      child: Column(
        children: [
          18.sizeBoxH,
          GridView.builder(
            padding: EdgeInsets.zero,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12,
              crossAxisSpacing: 5,
              childAspectRatio: 1,
            ),
            itemCount: recom?.anchors?.length ?? 0,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              LiveAnchor? model = recom?.anchors?[index];
              return LiveItemWidget(showType: 0, anchor: model);
            },
          ),
        ],
      ),
    );
  }

  //六圆形
  _buildsSixRound(LiveRecom? recom) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
          Color(0xffE97EA1).withOpacity(0),
          Color(0xffE97EA1).withOpacity(.2),
          Color(0xffE97EA1).withOpacity(0),
        ]),
      ),
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      child: Column(
        children: [
          18.sizeBoxH,
          Image.asset('assets/images/live_images/six_round_bg.webp', height: 45),
          18.sizeBoxH,
          GridView.builder(
            padding: EdgeInsets.zero,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12,
              crossAxisSpacing: 20,
              childAspectRatio: 108 / 164,
            ),
            itemCount: recom?.anchors?.length ?? 0,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              LiveAnchor? model = recom?.anchors?[index];
              return LiveItemWidget(showType: 1, anchor: model);
            },
          ),
          10.sizeBoxH,
        ],
      ),
    );
  }

  //四宫格
  _buildsFourGrid(LiveRecom? recom) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
          Color(0xff6F59FB).withOpacity(0),
          Color(0xff6F59FB).withOpacity(.2),
          Color(0xff6F59FB).withOpacity(0),
        ]),
      ),
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      child: Column(
        children: [
          18.sizeBoxH,
          Image.asset('assets/images/live_images/four_grid_bg.webp', height: 45),
          18.sizeBoxH,
          GridView.builder(
            padding: EdgeInsets.zero,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 12,
              crossAxisSpacing: 7,
              childAspectRatio: 1,
            ),
            itemCount: recom?.anchors?.length ?? 0,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              LiveAnchor? model = recom?.anchors?[index];
              return LiveItemWidget(showType: 2, anchor: model, index: index);
            },
          ),
          18.sizeBoxH,
        ],
      ),
    );
  }

  //六宫格
  _buildsSixGrid(LiveRecom? recom) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
          Color(0xffFF6730).withOpacity(0),
          Color(0xffFF6730).withOpacity(.2),
          Color(0xffFF6730).withOpacity(0),
        ]),
      ),
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      child: Column(
        children: [
          18.sizeBoxH,
          Image.asset('assets/images/live_images/six_grid_bg.webp', height: 36),
          18.sizeBoxH,
          GridView.builder(
            padding: EdgeInsets.zero,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12,
              crossAxisSpacing: 5,
              childAspectRatio: 1,
            ),
            itemCount: recom?.anchors?.length ?? 0,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              LiveAnchor? model = recom?.anchors?[index];
              return LiveItemWidget(showType: 3, anchor: model);
            },
          ),
        ],
      ),
    );
  }

  //横向滑动
  _buildsHorizontalSlide(LiveRecom? recom) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
          Color(0xffFF8E8E).withOpacity(0),
          Color(0xffFF8E8E).withOpacity(.2),
          Color(0xffFF8E8E).withOpacity(0),
        ]),
      ),
      child: Column(
        children: [
          18.sizeBoxH,
          Image.asset('assets/images/live_images/hori_slide_bg.webp', height: 28),
          18.sizeBoxH,
          Container(
            height: 175,
            alignment: Alignment.bottomRight,
            child: Swiper(
              autoplay: true,
              autoplayDelay: 5000,
              viewportFraction: 0.8,
              scale: 0.93,
              itemCount: recom?.anchors?.length ?? 0,
              itemBuilder: (c, index) {
                LiveAnchor? model = recom?.anchors?[index];
                return LiveItemWidget(showType: 4, anchor: model);
              },
            ),
          ),
          18.sizeBoxH,
        ],
      ),
    );
  }

  //推荐无限下滑列表
  _buildRecommendList(List<LiveAnchor>? anchors) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 28),
      child: GridView.builder(
        padding: EdgeInsets.zero,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 12,
          crossAxisSpacing: 5,
          childAspectRatio: 168 / 105,
        ),
        itemCount: anchors?.length ?? 0,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          LiveAnchor? model = anchors?[index];
          return LiveItemWidget(showType: 5, anchor: model);
        },
      ),
    );
  }
}
